import { makeMap } from './makeMap'

// 定义一个空对象，开发环境下使用 Object.freeze 冻结对象，生产环境下直接返回空对象
export const EMPTY_OBJ: { readonly [key: string]: any } = __DEV__
  ? Object.freeze({})
  : {}

// 定义一个空数组，开发环境下使用 Object.freeze 冻结数组，生产环境下直接返回空数组
export const EMPTY_ARR: readonly never[] = __DEV__ ? Object.freeze([]) : []

// 定义一个空函数，通常用于占位或默认回调
export const NOOP = (): void => { }

/**
 * 始终返回 false 的函数
 */
export const NO = () => false

// 判断字符串是否以 'on' 开头，并且第三个字符不是小写字母
export const isOn = (key: string): boolean =>
  key.charCodeAt(0) === 111 /* o */ &&
  key.charCodeAt(1) === 110 /* n */ &&
  // 大写字母
  (key.charCodeAt(2) > 122 || key.charCodeAt(2) < 97)

// 判断字符串是否以 'onUpdate:' 开头，用于识别模型监听器
export const isModelListener = (key: string): key is `onUpdate:${string}` =>
  key.startsWith('onUpdate:')

// 扩展函数，等同于 Object.assign
export const extend: typeof Object.assign = Object.assign

// 从数组中移除指定元素
export const remove = <T>(arr: T[], el: T): void => {
  const i = arr.indexOf(el)
  if (i > -1) {
    arr.splice(i, 1)
  }
}

const hasOwnProperty = Object.prototype.hasOwnProperty
// 判断对象是否拥有指定属性
export const hasOwn = (
  val: object,
  key: string | symbol,
): key is keyof typeof val => hasOwnProperty.call(val, key)

// 判断是否为数组
export const isArray: typeof Array.isArray = Array.isArray
// 判断是否为 Map 对象
export const isMap = (val: unknown): val is Map<any, any> =>
  toTypeString(val) === '[object Map]'
// 判断是否为 Set 对象
export const isSet = (val: unknown): val is Set<any> =>
  toTypeString(val) === '[object Set]'

// 判断是否为 Date 对象
export const isDate = (val: unknown): val is Date =>
  toTypeString(val) === '[object Date]'
// 判断是否为 RegExp 对象
export const isRegExp = (val: unknown): val is RegExp =>
  toTypeString(val) === '[object RegExp]'
// 判断是否为函数
export const isFunction = (val: unknown): val is Function =>
  typeof val === 'function'
// 判断是否为字符串
export const isString = (val: unknown): val is string => typeof val === 'string'
// 判断是否为 Symbol
export const isSymbol = (val: unknown): val is symbol => typeof val === 'symbol'
// 判断是否为对象
export const isObject = (val: unknown): val is Record<any, any> =>
  val !== null && typeof val === 'object'

// 判断是否为 Promise 对象
export const isPromise = <T = any>(val: unknown): val is Promise<T> => {
  return (
    (isObject(val) || isFunction(val)) &&
    isFunction((val as any).then) &&
    isFunction((val as any).catch)
  )
}

// 获取对象的 toString 方法
export const objectToString: typeof Object.prototype.toString =
  Object.prototype.toString
// 获取值的类型字符串
export const toTypeString = (value: unknown): string =>
  objectToString.call(value)

// 获取值的原始类型
export const toRawType = (value: unknown): string => {
  // 从类似 "[object RawType]" 的字符串中提取 "RawType"
  return toTypeString(value).slice(8, -1)
}

// 判断是否为纯对象
export const isPlainObject = (val: unknown): val is object =>
  toTypeString(val) === '[object Object]'

// 判断是否为整数键
export const isIntegerKey = (key: unknown): boolean =>
  isString(key) &&
  key !== 'NaN' &&
  key[0] !== '-' &&
  '' + parseInt(key, 10) === key

// 判断是否为保留属性
export const isReservedProp: (key: string) => boolean = /*@__PURE__*/ makeMap(
  // 开头的逗号是故意的，以便空字符串 "" 也被包括在内
  ',key,ref,ref_for,ref_key,' +
  'onVnodeBeforeMount,onVnodeMounted,' +
  'onVnodeBeforeUpdate,onVnodeUpdated,' +
  'onVnodeBeforeUnmount,onVnodeUnmounted',
)

// 判断是否为内置指令
export const isBuiltInDirective: (key: string) => boolean =
  /*@__PURE__*/ makeMap(
  'bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text,memo',
)

// 缓存字符串函数的工具函数
const cacheStringFunction = <T extends (str: string) => string>(fn: T): T => {
  const cache: Record<string, string> = Object.create(null)
  return ((str: string) => {
    const hit = cache[str]
    return hit || (cache[str] = fn(str))
  }) as T
}

const camelizeRE = /-(\w)/g
/**
 * 将连字符字符串转换为驼峰式
 * @private
 */
export const camelize: (str: string) => string = cacheStringFunction(
  (str: string): string => {
    return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''))
  },
)

const hyphenateRE = /\B([A-Z])/g
/**
 * 将驼峰式字符串转换为连字符式
 * @private
 */
export const hyphenate: (str: string) => string = cacheStringFunction(
  (str: string) => str.replace(hyphenateRE, '-$1').toLowerCase(),
)

/**
 * 将字符串首字母大写
 * @private
 */
export const capitalize: <T extends string>(str: T) => Capitalize<T> =
  cacheStringFunction(<T extends string>(str: T) => {
    return (str.charAt(0).toUpperCase() + str.slice(1)) as Capitalize<T>
  })

// 比较两个值是否发生变化，考虑 NaN 的情况
export const hasChanged = (value: any, oldValue: any): boolean =>
  !Object.is(value, oldValue)

// 定义对象属性
export const def = (
  obj: object,
  key: string | symbol,
  value: any,
  writable = false,
): void => {
  Object.defineProperty(obj, key, {
    configurable: true,
    enumerable: false,
    writable,
    value,
  })
}
